package com.movefeng.hexoblogadmin.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.movefeng.hexoblogadmin.utils.EncryptUtils;
import com.movefeng.hexoblogadmin.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Set;

/**
 * @author csp1999
 */
@Slf4j
@Component
public class AdminInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private FindByIndexNameSessionRepository<? extends Session> sessionRepository;

    public AdminInterceptor(FindByIndexNameSessionRepository<? extends Session> sessionRepository) {
        this.sessionRepository = sessionRepository;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = false;
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();

        String jsessionid = request.getHeader("jsessionid");
        if (jsessionid != null && !"".equals(jsessionid)) {
            Map<String, ? extends Session> sessionsMap = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "admin");
            Set<String> keySet = sessionsMap.keySet();
            jsessionid = EncryptUtils.base64Decode(jsessionid);
            if (keySet.contains(jsessionid)) {
                flag = true;
            } else {
                Result result = new Result(Result.Code.LOGIN_INFO_EXPIRE, "登录信息过期");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            }
        } else {
            HttpSession session = request.getSession();
            Object admin = session.getAttribute("admin");
            if (admin != null) {
                flag = true;
            } else {
                Result result = new Result(Result.Code.LOGIN_INFO_EXPIRE, "登录信息过期");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            }
        }
        return flag;
    }
}
